package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.Utilities;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜品管理
 * */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    /**
     * 新增菜品
     * */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     * */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //分页构造器
        Page<Dish> page1 = new Page<>(page,pageSize);
        Page<DishDto> page2 = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(page1,queryWrapper);
        //对象拷贝,第三个参数为排除哪个属性
        BeanUtils.copyProperties(page1,page2,"records");
        List<Dish> records = page1.getRecords();
        List<DishDto> list = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if(byId != null){
                String categoryName = byId.getName();
                dishDto.setCategoryName(categoryName);
            }
            list.add(dishDto);
        }
        page2.setRecords(list);
        return R.success(page2);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }

    /**
     * 批量和单个启售停售菜品
     * */
    @Transactional
    @PostMapping("/status/{id}")
    public R<String> status(@PathVariable int id,String ids){
        log.info("修改菜品启用状态，id为:{},{}",id,ids);
        String [] arr = ids.split(",");
        for (String s : arr) {
            Dish dish = dishService.getById(s);
            if(dish.getStatus()==id){
                if(dish.getStatus()==0){
                    return R.error(dish.getName()+"菜品已是停售状态，无法修改");
                }else{
                    return R.error(dish.getName()+"菜品已是启售状态，无法修改");
                }
            }
        }
        for (String s : arr) {
            Dish dish = dishService.getById(s);
            dish.setStatus(id);
            dishService.updateById(dish);
        }
        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * */
    @DeleteMapping
    public R<String> delete(String ids){
        log.info("删除菜品的id为：{}",ids);
        dishService.deletearr(ids);

        return R.success("删除成功");
    }

    /**
     * 查询套餐菜单中每个分类对应的菜品信息
     * */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加启售状态的查询
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加启售状态的查询
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish record : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if(byId != null){
                String categoryName = byId.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品id
            Long dishId = record.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            dishDto.setFlavors(dishFlavorService.list(queryWrapper1));
            dishDtoList.add(dishDto);
        }


        return R.success(dishDtoList);
    }
}
